-- UIMgr
-- Create by weism
-- UI界面的启动流程

require("game/ui/base/util");
require("game/ui/base/FormBase");
-- require("game/ui/sequence/Sequence");
require("game/ui/scene_sequence/SceneSequence");
require("game/ui/sky_sequence/SkySequence");
require("game/ui/sky_sequence/SkySequenceList");
require("game/ui/UIConsts");
require("game/ui/base/TextColorM");
require("game/ui/base/TextStyleM");
require("game/ui/base/AttribColorM");
require("game/ui/base/AnimationCacheM");
require("game/ui/base/AlignM");
require("game/ui/base/BackEvent");
require("game/ui/base/LaunchType");

module("UIMgr", package.seeall);

STATE_LOGIN = 1;
STATE_CREATE_CHAR = 2;
STATE_MAIN = 3;

MAIN_MAP_ZORDER = -1000;

--英雄子菜单的ZOrder
HERO_SUBMENU_ZORDER = 1000;

-- 头部菜单的ZOrder
TOP_MENU_ZORDER = 1001;

-- 奖励窗口的Zorder
BONUS_NOTIFY_ZORDER = 10000;


--当前状态
local curentState = STATE_AUTOPATCH;

-- 当前场景
curentScene = nil;

function startUI()
    setCurState(STATE_LOGIN);
end

-- 更新主界面
local function updateUI()
    if curentState == STATE_LOGIN then
        showLogin();
    elseif curentState == STATE_CREATE_CHAR then
        -- 不需要
    elseif curentState == STATE_MAIN then
        enterMain();
    else

    end
end

-- 改变状态
function setCurState(state)
    curentState = state;
    updateUI();
end

--切换到目标场景
local function switchToScene(scene)
    if cc.Director:getInstance():getRunningScene() then
        cc.Director:getInstance():replaceScene(scene);
    else
        cc.Director:getInstance():runWithScene(scene);
    end

    -- clearUnusedTextures();
end

-- 登陆场景
function showLogin()
    local scene = require("game/scene/LoginScene");
    local loginScene = scene.create();
    curentScene = loginScene;
    switchToScene(loginScene);
end

-- 游戏场景
function enterMain()
    local scene = require("game/scene/GameScene");
    local gameScene = scene.create();
    curentScene = gameScene;
    switchToScene(gameScene);
end

-- 切换语言后，重新加载主场景
function reloadMain()
    local scene = require("game/scene/TransScene");
    local transScene = scene.create();
    switchToScene(transScene);

    curentScene = transScene;
end

-- 获取当前场景
function getCurrentScene()
    return curentScene;
end

-- 获取顶部菜单高度
function getTopMenuHeight()
    local w = cc.Director:getInstance():getOpenGLView():getFrameSize().width;
    return 135 * w / DESIGN_WIDTH;
end

function isClearUnsedTextures(force)
    -- 如果内存不高(小于150M，ios下100M)，就不要做内存释放这个操作
    -- TODO: 图片等资源也需要统计进来，chenx搞定
    local size = 153600; -- 150M
    if isIosPlatform() then size = 100 * 1024 end
    local totalBytes = cc.Director:getInstance():getTextureCache():getCachedTextureBytes() / 1024;
    totalBytes = totalBytes + collectgarbage("count");

    if totalBytes < size and force == nil then
        cclog(string.format("占用内存为 %.02d M，不清理内存。", totalBytes / 1024));
        return false;
    end

    return true;
end

-- 清除无用纹理
function clearUnusedTextures(skipCsbData, force)
    if not isClearUnsedTextures(force) then
        return;
    end

    Profiler.funcBegin("clearUnusedTextures:AudioM");
    AudioM.purge();
    Profiler.funcEnd("clearUnusedTextures:AudioM");

    Profiler.funcBegin("clearUnusedTextures:AnimationCacheM");
    -- 清除动画缓存
    AnimationCacheM.purgeCache();
    Profiler.funcEnd("clearUnusedTextures:AnimationCacheM");

    if not skipCsbData then
        Profiler.funcBegin("clearUnusedTextures:CSLoader");
        cc.CSLoader:getInstance():purge();
        Profiler.funcEnd("clearUnusedTextures:CSLoader");
    end

    Profiler.funcBegin("clearUnusedTextures:TextureCache");
    -- 清除纹理缓存
    cc.Director:getInstance():purgeCachedData();
    Profiler.funcEnd("clearUnusedTextures:TextureCache");

    Profiler.funcBegin("clearUnusedTextures:LuaGC");
    -- lua GC
    collectgarbage("collect");
    Profiler.funcEnd("clearUnusedTextures:LuaGC");

    if DEBUG_MODE == 1 then
        local totalBytes = cc.Director:getInstance():getTextureCache():getCachedTextureBytes();
        print("[STAT]texture mem size:"..(totalBytes/1024/1024).."M");
        printLuaMemSize("STAT");
    end
end

-- 尝试清除无用纹理
function tryClearUnusedTextures()
    local function delay()
        -- 需要清除的时候才去显示
        if UIMgr.isClearUnsedTextures() then
            showCommunicatingForm();
            local function delay2()
                -- 清除无用纹理
                UIMgr.clearUnusedTextures();

                closeCommunicatingForm();
            end

            performWithDelay(UIMgr.getCurrentScene(), delay2, 0.1);
        end
    end
    performWithDelay(UIMgr.getCurrentScene(), delay, 0.01);
end

-- 测试用
function clearRefList()
    cc.Ref:clear();
end

function printRefList()
    cc.Ref:printLeaks();
end

-- 清空纹理
function cleanTextures()
    cc.SpriteFrameCache:destroyInstance();
    cc.Director:getInstance():getTextureCache():removeAllTextures();
end

-- 处理返回键按下事件
function handleBackEvent()
    -- 调用当前模态窗口的返回处理事件
    local uiCurDialog = getCurrentScene():getCurrentDialog();
    if uiCurDialog and uiCurDialog.backEventHandler then
        if uiCurDialog.backNode == nil or uiCurDialog.backNode:isVisible() then
            uiCurDialog.backEventHandler(uiCurDialog.backNode, ccui.TouchEventType.ended);
        end
        return;
    end

    -- 调用当前窗口的返回处理事件
    local uiCurForm = getCurrentScene():getCurrentForm();
    if uiCurForm and uiCurForm.backEventHandler then
        if uiCurForm.backNode == nil or uiCurForm.backNode:isVisible() then
            uiCurForm.backEventHandler(uiCurForm.backNode, ccui.TouchEventType.ended);
        end
    end
end


